package com.tqz.rc.server.cluster;

import com.tqz.rc.common.util.EnvUtil;
import com.tqz.rc.common.util.InetUtils;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2021/9/24 10:49
 */
@Component
public class ServiceMemberManager {

    /**
     * Cluster node list.
     */
    private volatile ConcurrentSkipListMap<String, Member> serverList;

    /**
     * self member obj.
     */
    private volatile Member self;

    private String localAddress;

    private int port;

    public ServiceMemberManager() {
        this.serverList = new ConcurrentSkipListMap<>();
        init();
    }

    private void init() {
        this.port = EnvUtil.getProperty(MemberUtils.SERVER_PORT_PROPERTY, Integer.class, MemberUtils.DEFAULT_SERVER_PORT);
        this.localAddress = InetUtils.getSelfIP() + ":" + port;
        this.self = MemberUtils.singleParse(this.localAddress);
    }

    public void memberChange(Collection<Member> members) {
        serverList = (ConcurrentSkipListMap) members;
    }

    public Collection<Member> allMembers() {
        // We need to do a copy to avoid affecting the real data
        HashSet<Member> set = new HashSet<>(serverList.values());
        set.add(self);
        return set;
    }
}
